package com.lancoo.znbkxx.teacher.ui.fragment

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import android.widget.TextView
import androidx.annotation.Dimension
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext.Companion.COURSE_CLASSID
import com.lancoo.znbkxx.teacher.Ext.Companion.COURSE_CLASSNAME
import com.lancoo.znbkxx.teacher.Ext.Companion.GLOBAL_GRADE
import com.lancoo.znbkxx.teacher.Ext.Companion.INFOLIST
import com.lancoo.znbkxx.teacher.Ext.Companion.STAGE_NO
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.base.SharedPreferencesHelper
import com.lancoo.znbkxx.teacher.databinding.FmtCommentsBinding
import com.lancoo.znbkxx.teacher.ui.activity.MainActivity
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.MkUtils
import com.lancoo.znbkxx.teacher.viewmodel.CommentViewModel
import com.lancoo.znbkxx.teacher.widget.ClassMenu

import kotlinx.android.synthetic.main.fmt_comments.*
import kotlinx.android.synthetic.main.fmt_comments.tv_title

/**
 * @author : Admin
 * @date   : 2019/7/18 16:58
 * @desc   :
 */
class CommentsFragment : BaseVMFragment<CommentViewModel, FmtCommentsBinding>(),
        BaseQuickAdapter.OnItemClickListener, View.OnClickListener {
    private val tabs = arrayOf("未辅导", "已辅导")
    private var classPosition = 0
    private val classPopupWindow by lazy {
        val list = mutableListOf<String>()
        INFOLIST!!.forEach {
            list.add(it.CourseClassName)
        }
        ClassMenu(requireContext(), list, this)
    }

    companion object {
        private const val TITLE = "title"
        fun newInstance(title: String): CommentsFragment {
            val fragment = CommentsFragment()
            val bundle = Bundle()
            bundle.putString(TITLE, title)
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun setLayoutID(): Int {
        return R.layout.fmt_comments
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun providerVMClass(): Class<CommentViewModel>? {
        return CommentViewModel::class.java
    }

    override fun initView() {
        binding.model = viewModel
        tv_title.typeface = Typeface.createFromAsset(requireContext().assets,
                "fonts/cool_black.TTF")
        initViewpager()
        initSpinner()
    }

    private fun initViewpager() {
        vp.isUserInputEnabled = false
        vp.offscreenPageLimit = 1
        vp.adapter = object : FragmentStateAdapter(childFragmentManager, lifecycle) {
            override fun getItemCount(): Int {
                return 2
            }

            override fun createFragment(position: Int): Fragment {
                return HardSolutionListFragment().apply {
                    arguments = bundleOf(Pair("type", position))
                }
            }
        }
        tbl.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.customView?.findViewById<TextView>(R.id.tv)?.apply {
                    setBackgroundResource(R.drawable.aibk_bg_tab_hardsolution_select)
                    setTextSize(Dimension.SP, 18f)
                    height = DensityUtils.dp2px(requireContext(), 50f)
                }
                tab?.customView?.findViewById<View>(R.id.view)?.visibility = View.GONE
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.customView?.findViewById<TextView>(R.id.tv)?.apply {
                    setBackgroundResource(
                            if (tab.position == 0) R.drawable.aibk_bg_tab_hardsolution_left else R.drawable.aibk_bg_tab_hardsolution_right)
                    setTextSize(Dimension.SP, 14f)
                    height = DensityUtils.dp2px(requireContext(), 40f)
                }
                tab?.customView?.findViewById<View>(R.id.view)?.visibility = View.VISIBLE
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })
        TabLayoutMediator(tbl, vp) { tab, position ->
            tab.setCustomView(R.layout.item_tab_hard_selected)
            tab.customView?.findViewById<TextView>(R.id.tv)?.text = tabs[position]
        }.attach()
        tbl.getTabAt(1)?.select()
        tbl.getTabAt(0)?.select()
    }

    private fun initSpinner() {
        binding.tvClassname.text = COURSE_CLASSNAME
        binding.tvClassname.setOnClickListener(this)
    }

    fun setClass(name: String, position: Int) {
        if (classPosition == position) {
            return
        }
        classPosition = position
        classPopupWindow.adapter.apply {
            posList.forEach {
                posList[it.key] = false
            }
            posList[position] = true
            notifyDataSetChanged()
        }
        binding.tvClassname.text = name
        initComment()
    }

    private fun initComment() {
        (activity as MainActivity).loadingDialog.show()
        viewModel.getHardSolutionList(CurrentUser.Token, CurrentUser.UserID, COURSE_CLASSID,
                CurrentUser.SchoolID)
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.tv_classname, R.id.iv_switch -> {
                classPopupWindow.setOnDismissListener {
                    val lp = requireActivity().window.attributes
                    lp.alpha = 1.0f
                    requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                    requireActivity().window.attributes = lp
                }
                classPopupWindow.showAsDropDown(binding.tvClassname, -100, 10)
                val lp = requireActivity().window.attributes
                lp.alpha = 0.8f
                requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                requireActivity().window.attributes = lp
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun startObserve() {
        viewModel.mHardSolution.observe(this, Observer { it ->
            Handler().post { (activity as MainActivity).loadingDialog.dismiss() }
            val isAgreePermissions = SharedPreferencesHelper.getBoolean("isAgreePermissions", false)
            if (it.UnFinishedList.size + it.FinishedList.size > 0 && isAgreePermissions) {
                binding.cardView.visibility = View.VISIBLE
                binding.group.visibility = View.GONE
                binding.progressBar.setPercentData(
                        it.FinishedList.size / (it.UnFinishedList.size + it.FinishedList.size).toFloat() * 100,
                        "%", DecelerateInterpolator(), 0)
                val list = it.TypeList.sortedByDescending { it.AvgScoreRate }
                if (list.size > 1) {
                    binding.tvTypeHigh.text =
                            "${if (list[0].GenreName.isBlank()) list[0].TypeName else list[0].GenreName}/${if (list[1].GenreName.isBlank()) list[1].TypeName else list[1].GenreName}"
                } else {
                    binding.tvTypeHigh.text =
                            if (list[0].GenreName.isBlank()) list[0].TypeName else list[0].GenreName
                }
            } else {
                binding.cardView.visibility = View.GONE
                binding.group.visibility = View.VISIBLE
                binding.progressBar.setPercentData(0f, "%", DecelerateInterpolator(), 0)
                return@Observer
            }
        })
        viewModel.reviewedDetail.observe(this, Observer {
            if (it.NotReviewedList.size == 0 && it.ReviewedList.size == 0) {
                MyToast.showToast("暂无数据")
            } else {
//                val reviewedDialog = ReviewedDialog.newInstance(it, null).apply {
//                    setStyle(DialogFragment.STYLE_NORMAL, R.style.Theme_dialog)
//                }
//                reviewedDialog.show(parentFragmentManager, "reviewedDialog")
                val stuProgressDialog = StuProgressDialog().apply {
                    arguments = bundleOf(Pair("reviewed", it), Pair("type", 3))
                }
                stuProgressDialog.show(parentFragmentManager, "")
            }
            Handler().post { (activity as MainActivity).loadingDialog.dismiss() }
        })
        viewModel.mErrorMsg.observe(this,
                Observer { Handler().post { (activity as MainActivity).loadingDialog.dismiss() } })
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        COURSE_CLASSNAME = INFOLIST!![position].CourseClassName
        MkUtils.encode("COURSE_CLASSNAME",COURSE_CLASSNAME)
        COURSE_CLASSID = INFOLIST!![position].CourseClassID
        MkUtils.encode("COURSE_CLASSID",COURSE_CLASSID)
        GLOBAL_GRADE = INFOLIST!![position].GlobalGrade
        MkUtils.encode("GLOBAL_GRADE",GLOBAL_GRADE)
        STAGE_NO = when (GLOBAL_GRADE) {
            "K6", "K7", "K8", "K9" -> "B"
            else -> "C"
        }
        setClass(COURSE_CLASSNAME, position)
        (parentFragmentManager.findFragmentByTag("f0") as AIPreparationFragment).setClass(
                COURSE_CLASSNAME,
                position)
        classPopupWindow.dismiss()
    }

    override fun onResume() {
        super.onResume()
        initComment()
    }
}